<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <!-- 
          {
            id: 7650,
            userId: "8a462598-b621-4684-bb17-000cf4e2d2b8",
            skuId: 6042,
            cartPrice: 3288,
            skuNum: 3,
            imgUrl:
              "http://47.93.148.192:8080/group1/M00/00/01/rBHu8l-rfvmAIpgZAAIvrX6L9fo612.jpg",
            skuName: "小米10-1",
            isChecked: 1,
            skuPrice: 3288,
          };
         -->
        <ul class="cart-list" v-for="goods in cartList" :key="goods.id">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="!!goods.isChecked"
              @change="setGoodsIsChecked(goods)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="goods.imgUrl" :alt="goods.skuName" />
            <div class="item-msg">
              {{ goods.skuName }}
            </div>
          </li>
          <!-- <li class="cart-list-con3">
            <div class="item-txt">语音升级款</div>
          </li> -->
          <li class="cart-list-con4">
            <span class="price">{{ goods.cartPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <InputNumber
              :value="goods.skuNum"
              @input="updateCartNum(goods, $event)"
              :max="100"
            />
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ goods.cartPrice * goods.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a href="#none" class="sindelet" @click="showDelCart(goods.skuId)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <!-- <input class="chooseAll" type="checkbox" :checked="" @change=""/> -->
        <input class="chooseAll" type="checkbox" v-model="checkedAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="showDelCheckedCart">删除选中的商品</a>
        <a>移到我的关注</a>
        <a>清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ isCheckedNum }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" @click="toTrade">结算</a>
        </div>
      </div>
    </div>

    <Dialog :visible.sync="visible">
      <template v-slot:header>
        警告
      </template>
      <template>
        是否要删除{{ isDelCheckedCart ? "所有已选中的" : "当前" }}商品?
      </template>
      <template #footer>
        <div class="btn-wrap">
          <button class="btn" @click="visible = false">取消</button>
          <button class="btn primary" @click="delCart">确认</button>
        </div>
      </template>
    </Dialog>

    <Dialog :visible.sync="toTradeVisible">
      <template v-slot:header>
        警告
      </template>
      <template>
        至少选中一个商品
      </template>
    </Dialog>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
import {
  reqGetCartList,
  reqUpdateCartChecked,
  reqDelCart,
  reqAddCart,
} from "@/api/shopcart";
import Dialog from "@/components/Dialog";
import InputNumber from "@/components/InputNumber";

export default {
  name: "ShopCart",
  data() {
    return {
      cartList: [],
      visible: false,
      toTradeVisible: false,
      skuId: "",
      isDelCheckedCart: false,
    };
  },
  async mounted() {
    const res = await reqGetCartList();
    // && 第一个条件为真，整体表达式就会把第二个表达式返回
    // 第一个条件为假，直接返回第一个表达式
    // this.cartList = res[0] && res[0].cartInfoList;
    // 基本数据类型：Number String Boolean Undefined Null Symbol(ES6) BigInt(ES10)
    // 引用数据类型：Object Array Function
    // ES11 可选链
    this.cartList = res[0] ? res[0].cartInfoList : [];
  },
  methods: {
    // 更新商品isChecked
    async setGoodsIsChecked(goods) {
      // reqUpdateCartChecked(skuId, isChecked === 0 ? 1 : 0);
      const isChecked = 1 - goods.isChecked;
      // 更新客户端数据
      goods.isChecked = isChecked;
      // 更新服务器数据
      await reqUpdateCartChecked(goods.skuId, isChecked);
    },
    // 显示删除对话框
    showDelCart(skuId) {
      this.isDelCheckedCart = false;
      this.skuId = skuId;
      this.visible = true;
    },
    // 删除商品
    async delCart() {
      if (this.isDelCheckedCart) {
        this.cartList = this.cartList.filter((goods) => {
          const isChecked = !!goods.isChecked;
          if (isChecked) {
            reqDelCart(goods.skuId);
          }
          return !isChecked;
        });

        this.visible = false;
        return;
      }

      // 删除单个
      const { skuId } = this;
      // 删除本地数据
      this.cartList = this.cartList.filter((goods) => goods.skuId !== skuId);
      this.visible = false;
      // 删除服务器数据
      await reqDelCart(skuId);
    },
    showDelCheckedCart() {
      this.isDelCheckedCart = true;
      this.visible = true;
    },
    // 更新商品数量
    updateCartNum: debounce(function(goods, num) {
      // console.log(goods.skuId, num);
      reqAddCart(goods.skuId, num - goods.skuNum);
      goods.skuNum = num;
    }, 1000),
    // 跳转到trade页面
    toTrade() {
      if (this.isCheckedNum === 0) {
        this.toTradeVisible = true;
        return;
      }
      this.$router.push("/trade");
    },
  },
  computed: {
    checkedAll: {
      get() {
        // return !this.cartList.some((goods) => goods.isChecked === 0);
        return (
          this.cartList.every((goods) => goods.isChecked === 1) &&
          this.cartList.length > 0
        );
      },
      set(val) {
        // val true/false
        // 将所有商品的isChecked更新成val
        const isChecked = val ? 1 : 0;

        this.cartList.forEach((goods) => {
          // 不改
          if (goods.isChecked === isChecked) return;

          this.setGoodsIsChecked(goods);
        });
      },
    },
    isCheckedNum() {
      return this.cartList.reduce((p, c) => {
        return p + (c.isChecked ? c.skuNum : 0);
      }, 0);
    },
    totalPrice() {
      return this.cartList.reduce((p, c) => {
        return p + (c.isChecked ? c.skuNum * c.cartPrice : 0);
      }, 0);
    },
  },
  components: {
    Dialog,
    InputNumber,
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 4.1667%;
        }

        .cart-list-con2 {
          width: 45%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con3 {
          width: 20.8333%;

          .item-txt {
            text-align: center;
          }
        }

        .cart-list-con4 {
          width: 12.5%;
        }

        .cart-list-con5 {
          width: 12.5%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 12.5%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 12.5%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn-wrap {
  float: right;
}
.btn {
  font-size: 12px;
  border: 1px solid #ccc;
  padding: 8px 15px;
  border-radius: 3px;
  outline: none;
  background: #fff;
  margin-left: 10px;
  cursor: pointer;
  &.primary {
    border: 1px solid #179ed3;
    background: #179ed3;
    color: #fff;
  }
}
</style>
